<template>
  <div class="flex flex-col h-full">
    <ReadCard
      ref="readCardRef"
      business-type="门诊退费"
      :call-back-data="formState"
      @read="onReadCardSuccess"
      @tab-change="onTabRadioChange"
      @change="onChangeCard"
    >
      <template #selfCost>
        <!-- <a-card :body-style="{ padding: '8px 12px' }"> -->
        <a-form ref="formRef" :model="formState" class="flex justify-between">
          <div class="flex">
            <a-form-item name="brName" class="w-[260px] mr-3 !mb-0">
              <SelectTable
                v-model:value="formState.brName"
                :search-params="{ stdate: formState.stdate, eddate: formState.eddate, miFlag: 0, cxtype: 'zf' }"
                type="门诊挂号患者列表退费"
                placeholder="姓名/助记码/卡号/手机号/身份证号"
                @select="onSelect"
              />
            </a-form-item>
            <a-form-item label="挂号时间" class="!mb-0">
              <div class="flex">
                <a-date-picker v-model:value="formState.stdate" placeholder="开始时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                <a-date-picker v-model:value="formState.eddate" class="ml-2" placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
              </div>
            </a-form-item>
          </div>
          <div>
            <a-button style="margin: 0 8px" @click="onClickReset">重置</a-button>
            <a-button type="primary" @click="chargeDetailList">刷新</a-button>
          </div>
        </a-form>
        <!-- </a-card> -->
      </template>
      <template #rightBtn>
        <div class="flex items-center">
          <a-button style="margin: 0 8px" @click="onClickReset">重置</a-button>
          <a-button type="primary" @click="chargeDetailList(readCardInfo.isgb ? 2 : 1, 'yb')">刷新</a-button>
        </div>
      </template>
    </ReadCard>
    <PatientInfoHeader :patient-info="patientInfo" :show-insurance="true" class="mt-2" @change="onClickReset">
      <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
      <div>
        <div class="flex items-center">
          <LabelValue label="卡号" :value="patientInfo.brId" :width="160" label-class="w-[52px] text-right" />
          <LabelValue label="病案号" :value="patientInfo[isBGMSG ? 'brBlkh' : 'oprSn']" :width="160" />
          <LabelValue label="科室" :value="patientInfo.ksmc" :width="160" />
          <LabelValue label="类别" :value="patientInfo.ghlb" :width="160" />
        </div>
        <div class="flex items-center">
          <LabelValue label="门诊号" :value="patientInfo.jzbh" :width="160" />
          <LabelValue label="病历号" :value="patientInfo[isBGMSG ? 'oprSn' : 'brBlkh']" :width="160" />
          <LabelValue label="医生" :value="patientInfo.empName" :width="160" />
          <LabelValue label="时间" :value="patientInfo.ghsj" :width="200" />
        </div>
      </div>
      <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
      <div class="ml-10">
        <div class="flex items-center">
          <LabelValue label="原票据号" :value="patientInfo.pjhm" :width="160" />
          <LabelValue v-if="patientInfo.zfmx" :width="300" :tooltip="true" :value="patientInfo.zfmx" />
          <LabelValue v-else label="支付" :value="'￥' + '0.00'" :width="160" />
        </div>
        <div class="flex items-center">
          <LabelValue label="原收费" :value="'￥' + patientInfo.zfy ? '￥' + formatAmount(patientInfo.zfy) : ''" :width="160" />
          <LabelValue label="时间" :value="patientInfo.sfsj" :width="220" />
        </div>
      </div>
    </PatientInfoHeader>
    <a-card class="mt-2">
      <div class="flex items-center justify-between mb-2">
        <BaseTitle title="费用明细" class="!w-20" />
        <div class="flex items-center">
          <div class="">
            <span class="text-red-500 mr-5"> 医保为全额退款，退款后请重新收取患者的正常费用 </span>
            <span class="mr-5"> 原收费合计:￥{{ formatAmount(patientInfo.bcysf) }} </span>
            <span class="text-red-500 mr-5"> 本次应退：￥{{ formatAmount(patientInfo.bcyt) }} </span>
          </div>
          <a-button type="primary" :disabled="!patientInfo.bcyt && patientInfo.bcyt != 0" @click="onClickCharge">退费</a-button>
        </div>
      </div>
      <BaseTable
        :loading="loading"
        column-code="00001119"
        fill
        :data-source="tableDataDetail"
        :row-class-name="(record) => (record.yzzt === 2 ? '!text-red-500' : '')"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'mc'">
            <MedicineInfo :value="{ mc: record?.mc, gg: record?.gg, cj: record?.cj }" />
          </template>
          <template v-if="column.dataIndex === 'action'">
            <BaseButton
              v-if="record.yzzt === 2"
              confirm-text="确认撤销退费？"
              type="link"
              size="small"
              :disabled="record.xmlb == 2 || record.xmlb == 4 || record.xmlb == 5"
              danger
              @click="onCancelReturn(record)"
              >撤销退费</BaseButton
            >
          </template>
        </template>
      </BaseTable>
    </a-card>
    <Refund
      v-model:open="priceOpen"
      :type="changeType"
      :business-data="{ pjhm: billNumber, ...patientInfo }"
      :charge-title="chargeTitle"
      :loading-state="loadingState"
      @success="onSuccessPrice"
    />
    <SelectBillModal v-model:open="openSelectModal" :resource-data="allBillData" @ok="onSelectBill" />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import BaseTitle from '@/components/BaseTitle'
import SelectTable from '@/components/SelectTable'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
// import { getSystemConfig } from '@/utils/systemConfig'
import Refund from '../components/RefundModal.vue'
import SelectBillModal from './SelectBillModal.vue'

const loading = ref(false)
const loadingState = ref(false)
const tableDataDetail = ref([])
const dayCount = Number(getSystemConfig('OUTP_DEFAULT_REFUND_SEARCH_INTERVAL') || 0)
const formState = ref({
  stdate: dayjs().subtract(dayCount, 'day').format('YYYY-MM-DD'),
  eddate: dayjs().format('YYYY-MM-DD'),
  kh: '',
  medType: '',
  bigIll: false,
  bigIllNum: undefined,
  indInjury: true,
  indInjuryNum: ''
})

const priceOpen = ref(false)
const patientInfo = ref({})
const billNumber = ref('')
const keycode = ref('')
const formRef = ref(null)
const serialList = ref([])
const tabActiveKey = ref('自费') //选中的tab
const readCardInfo = ref({})
const changeType = ref('zf') //zf 自费退号  yb 医保退号
const chargeTitle = ref('')
const readCardRef = ref(null)
const allBillData = ref([])
const openSelectModal = ref(false)
const onClickReset = () => {
  formState.value = {
    stdate: dayjs().subtract(dayCount, 'day').format('YYYY-MM-DD'),
    eddate: dayjs().format('YYYY-MM-DD'),
    kh: '',
    medType: '',
    bigIll: false,
    bigIllNum: undefined,
    indInjury: true,
    indInjuryNum: ''
  }
  formRef.value?.resetFields()
  patientInfo.value = {}
  billNumber.value = ''
  keycode.value = ''
  tableDataDetail.value = []
  readCardRef.value?.reset()
}

const onSelect = async (select) => {
  formState.value.brName = select.brName
  formState.value.jzbh = select.jzbh
  billNumber.value = select.pjhm
  keycode.value = select.keycode
  getOutpatientInfo()
  chargeDetailList()
}

// 计算应退分币误差
const getReceiptsAmount = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getPennyDiscount', {
    ysje: Number(patientInfo.value.bcyt), //应退金额
    yhje: 0 //优惠金额
  })
  if (code !== 0) return message.error(msg)
  patientInfo.value.bcyt = data.ssje
  patientInfo.value.fbyh = data.fbwc
}
// 计算实退分币误差
const getRealReceiptsAmount = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getPennyDiscount', {
    ysje: Number(patientInfo.value.bcyt_st), //实退金额
    yhje: 0 //优惠金额
  })
  if (code !== 0) return message.error(msg)
  patientInfo.value.bcyt_st = data.ssje
}

const onPrint = async (row = {}) => {
  if (row.jslxbz === 1) {
    //挂号收费
    const { code, msg, data } = await post('/outp/outPrint/getRegistrationBillPrint', { jzbh: row.keycode, pjhm: row.pjhm, sftfbs: 1 })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
  } else {
    //门诊收费
    const { code, msg, data } = await post('/outp/oupCharge/PrintMedicareCharges', { jzbh: row.keycode, pjhm: row.pjhm, sftfbs: 1 })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
  }
}
const onSuccessPrice = async (params) => {
  //自费
  loadingState.value = true
  if (tabActiveKey.value === '自费') {
    const { code, msg, data } = await post('/outp/oupCharge/doOutPRefund', { ...params, lshs: serialList.value, type: '0', fbyh: patientInfo.value.fbyh })
    loadingState.value = false
    if (code !== 0) return message.error(msg)
    priceOpen.value = false
    message.success(msg)
    onPrint(data)
    onClickReset()
  } else {
    //阜阳医保才会调壳验证密码
    let verRes = ''
    if (getSystemConfig('NMI_REGION_CODE') === '022' && formState.value.insutype === '310' && tabActiveKey.value === '社保卡') {
      verRes = await window.openExe?.iVerifyPIN()
    }
    const refundParams = {
      ...params,
      tftype: 'MZ',
      fbyh: patientInfo.value.fbyh,
      fphm: patientInfo.value.pjhm,
      jzbh: patientInfo.value.jzbh,
      tflx: patientInfo.value.tflx,
      lshs: patientInfo.value.dtlsh,
      kh: readCardInfo.value.kh,
      mdtrtCertNo: readCardInfo.value.mdtrtCertNo,
      mdtrtCertType: readCardInfo.value.mdtrtCertType,
      mmJson: verRes ? verRes : undefined,
      type: '0'
    }
    const { code, msg, data } = await post('outp/mzdj/medicalInsuranceRefundNumber', refundParams)
    loadingState.value = false
    priceOpen.value = false
    if (code !== 0) return message.error(msg || '退费失败')
    if (readCardInfo.value.isgb) {
      message.success(msg || '退费成功')
      onClickReset()
      onPrint(data)
    } else {
      let result = window.openExe?.readGHQQ(data)
      if (!window.openExe) {
        result =
          '{"response":{"czybm":"0000","sysResv":"1234567887654321Ti8ri8rTT8ir8rTiriT8TTir8Trrii8r8Tirc0a8006e","recvTime":"0004089798fc01d6","bbh":"0001","msgid":"9999999870020211229000824890","fhxx":"","jyqd":"10","xxlxm":"SK01","jyyzm":"","xzqhdm":"310000","jysj":"2021-12-29 11:16:38","jgdm":"99999998700","xxfhm":"P001","zdsbsbm":"","czyxm":"系统管理员","xxnr":{"translsh":"2101010287599771","zfcash":"5","dffj":"0.00","curaccountamt":"0.00","curaccount":"0.00","tc":"0.00","tccash":"0.00","dffjhisaccount":"0.00","cardid":"N02423258","accountattr":"1000000000000000","tchisaccount":"0.00","hisaccount":"0.00","dffjcash":"0.00","cardtype":"1","hisaccountamt":"0.00","personname":"测试卡0800"}}}'
      }
      const res1 = await post('outp/mzdj/doCallbackAPi', {
        jsonStr: result,
        jzbh: data.jzbh,
        request: {
          ...refundParams
        }
      })
      if (res1.code !== 0) return message.error(res1.msg || '退费失败')
      message.success(msg || '退费成功')
      onClickReset()
      onPrint(res1.data)
    }
  }
}

//获取门诊患者信息
const getOutpatientInfo = async () => {
  const { data, code } = await post('/outp/mzdj/getOutpRecordInfoYB', { mzjlbh: keycode.value, pjhm: billNumber.value })
  if (code === 0) {
    patientInfo.value = data
    formState.value.medTypeName = data?.medTypeName
    formState.value.insutypeName = data?.insutypeName
    formState.value.insutype = data?.insutype
    getReceiptsAmount()
    getRealReceiptsAmount()
  }
}
const chargeDetailList = async (miFlag = 0, cxtype = 'zf') => {
  const { code, data, msg } = await post('/outp/oupCharge/getOutpRefundFeeList', {
    pjhm: billNumber.value,
    miFlag: miFlag, // 医保状态 0：自费 1：五期 2：国家医保
    cxtype: cxtype //挂号退费检索 查询类别 自费:zf 医保:yb
  })
  if (code !== 0) return message.error(msg)
  tableDataDetail.value = data
  data.forEach((item) => {
    if (item.yzzt === 2) serialList.value.push(item.dtlsh)
  })
}
const onTabRadioChange = (val) => {
  tabActiveKey.value = val
  onClickReset()
}
const onChangeCard = (info) => {
  readCardInfo.value = { ...readCardInfo.value, ...info }
}
const onReadCardSuccess = async (info) => {
  readCardInfo.value.kh = info.ybkResonse?.kh
  readCardInfo.value = { ...info, ck: readCardInfo.value.ck, mdtrtCertNo: info.mdtrtCertNo, mdtrtCertType: info.mdtrtCertType } || {}
  if (!readCardInfo.value.brId) return message.error('当前患者未登记')
  const {
    code,
    data = {},
    msg
  } = await post('/outp/oupCharge/getOutpRefundPatientList', {
    brId: readCardInfo.value.brId,
    miFlag: readCardInfo.value.isgb ? 2 : 1,
    cxtype: 'yb'
  })
  if (code !== 0) return message.error(msg || '获取患者信息失败')
  if (data && data.length > 0) {
    if (data.length > 1) {
      allBillData.value = data
      openSelectModal.value = true
      return
    } else {
      formState.value.brName = data[0].brName
      // formState.value.medTypeName = data[0]?.medTypeName
      // formState.value.insutypeName = data[0]?.insutypeName
      formState.value.jzbh = data[0].jzbh
      billNumber.value = data[0].pjhm
      keycode.value = data[0].keycode
    }
  } else {
    return message.error('无患者信息')
  }
  getOutpatientInfo()
  formState.value = {
    stdate: dayjs().format('YYYY-MM-DD'),
    eddate: dayjs().format('YYYY-MM-DD'),
    ...readCardInfo.value.kh
  }
  chargeDetailList(readCardInfo.value.isgb ? 2 : 1, 'yb')
}
const onSelectBill = (select) => {
  // formState.value.medTypeName = select?.medTypeName
  // formState.value.insutypeName = select?.insutypeName
  formState.value.brName = select?.brName
  formState.value.jzbh = select?.jzbh
  billNumber.value = select?.pjhm
  keycode.value = select?.keycode
  getOutpatientInfo()
  formState.value = {
    stdate: dayjs().format('YYYY-MM-DD'),
    eddate: dayjs().format('YYYY-MM-DD'),
    ...readCardInfo.value.kh
  }
  chargeDetailList(readCardInfo.value.isgb ? 2 : 1, 'yb')
}
const onCancelReturn = async (record) => {
  const { code, msg } = await post('/outp/mzys/doMzyzZt', {
    keyCode: record.keycode
  })
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  getOutpatientInfo()
  if (tabActiveKey.value === '自费') {
    chargeDetailList()
  } else {
    chargeDetailList(readCardInfo.value.isgb ? 2 : 1, 'yb')
  }
}
const onClickCharge = () => {
  if (tabActiveKey.value === '自费') {
    changeType.value = 'zf'
  } else {
    changeType.value = 'yb'
    chargeTitle.value = `原收费${formatMoney(patientInfo.value.zfy)}  |  医保支付${formatMoney(patientInfo.value.ybje)}  分币￥${patientInfo.value.fbyh}`
  }
  priceOpen.value = true
}
const formatMoney = (val) => {
  if (val) {
    return '￥' + formatAmount(val)
  } else {
    return '￥' + '0.00'
  }
}
</script>
<style lang="less" scoped>
:deep(.ant-tabs-content-holder) {
  overflow: hidden;
}
:deep(.ant-radio-button-wrapper) {
  flex: 1;
  color: var(--primary-color);
  text-align: center;
  border-color: var(--primary-color);
  &::before {
    background-color: var(--primary-color);
  }
}
.w60 {
  width: 60px;
}
</style>
